package com.yeban.javase.day16.sync;

/**
 * @Desc TODO
 * @Author yeban
 * @Date 2025/10/30
 *
 * 需求：银行卡取款   确保取款的线程安全
 * 1.一方取款时，另一方不可以取款
 * 2.一方取完款后，余额归0，另一方不可以再进行取款，否则余额变成负数
 */
public class SyncTest2 {

    public static void main(String[] args) {

        BankCard bankCard = new BankCard(8000);

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                if(!bankCard.withdraw(800)){
                    break;
                }
            }
            }, "张三").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                if(!bankCard.withdraw(500)){
                    break;
                }
            }
            }, "李四").start();
    }
}

class BankCard {

    private double balance;

    public BankCard() {
    }

    public BankCard(double balance) {
        this.balance = balance;
    }

    public boolean withdraw(double money) {
        synchronized (this) {
            if(balance <= 0) {
                System.out.println(Thread.currentThread().getName() + "取款失败，余额不足！");
                return false;
            }

            if(balance >= money) {
                System.out.println(Thread.currentThread().getName() + "正在取款：" + money + "元");
                try {
                    Thread.sleep(1000); // 延迟操作时间
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                balance -= money;
                System.out.println(Thread.currentThread().getName() + "取款成功！剩余余额：" + balance + "元");
                return true;
            } else {
                System.out.println(Thread.currentThread().getName() + "取款失败，余额不足！当前余额：" + balance + "元");
                return false;
            }
        }
    }

    /**
     * 获取
     * @return balance
     */
    public double getBalance() {
        return balance;
    }

    /**
     * 设置
     * @param balance
     */
    public void setBalance(double balance) {
        this.balance = balance;
    }

    public String toString() {
        return "BankCard{balance = " + balance + "}";
    }
}
